package vcs

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"time"
)

type MavenConfig struct {
	GitProject GitProject
	Command    string
}

func moduleToPathPart(module string) string {
	if module == "gateway" {
		return "quan-gateway"
	}
	sprintf1 := fmt.Sprintf("quan-module-%s", module)
	sprintf2 := fmt.Sprintf("quan-module-%s-biz", module)
	join := filepath.Join(sprintf1, sprintf2)
	return join
}

func ModuleToJarName(module string) string {
	if module == "gateway" {
		return "quan-gateway.jar"
	}
	return fmt.Sprintf("quan-module-%s-biz.jar", module)
}

func ModuleToJarPath(module string, workDir string) string {
	if module == "gateway" {
		return filepath.Join(workDir, "quan-gateway.jar")
	}
	return filepath.Join(workDir, fmt.Sprintf("quan-module-%s-biz.jar", module))
}

func (mavenConfig *MavenConfig) ExecCommand() {
	cmd := exec.Command("mvn", "clean", mavenConfig.Command, "-DskipTests")
	cmd.Dir = GetGitProjectPath(&mavenConfig.GitProject)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		fmt.Printf("执行 Maven 打包命令失败: %v\n", err)
		return
	}
	time.Sleep(2 * time.Second)
	fmt.Println("Maven 打包成功!")
}

func pathExists(path string) bool {
	_, err := os.Stat(path)
	return !os.IsNotExist(err)
}

func (mavenConfig *MavenConfig) ModuleToJarPath(module string) string {
	basePath := GetGitProjectPath(&mavenConfig.GitProject)
	part := moduleToPathPart(module)
	jarName := ModuleToJarName(module)
	jarFullPath := filepath.Join(basePath, part, "target", jarName)
	if !pathExists(jarFullPath) {
		fmt.Println("路径:" + jarFullPath + "不存在!")
		os.Exit(1)
	}
	return jarFullPath
}
